package com.cq.xjms.web.actions.sys;


import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.CellType;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.cq.xjms.model.Clazz;
import com.cq.xjms.model.Course;
import com.cq.xjms.model.Score;
import com.cq.xjms.model.Student;
import com.cq.xjms.service.ScoreManager;
import com.cq.xjms.service.SysManager;
import com.cq.xjms.util.Constants;
import com.cq.xjms.util.PointUtil;
import com.cq.xjms.web.actions.BaseAction;
@SuppressWarnings("unchecked")
public class ScoreAction extends BaseAction{
	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(ScoreAction.class);
	private ScoreManager scoreManager;
	private Score score;
	private String type;
	private List<Score> scores;
	private Student student;
	private Clazz clazz;
	private Course course;
	private List<Course> courses;
	private List<Student> students;
	private SysManager sysManager;
	private String clazzarray;
	private String coursearray;
	private Map<String,Object> params = new HashMap<String,Object>();
	private File excel;
	private String excelFileName;
	private String excelContentType;
	
	
	public String saveScore(){
		try{
		String[] clazzarrays=clazzarray.split(",");
		String[] coursearrays=coursearray.split(",");
		score=new Score();
		for(int i=0;i<clazzarrays.length;i++){
			Map<String,Object> clazzparams = new HashMap<String,Object>();
			clazzparams.put("clazz_id", Long.valueOf(StringUtils.trim(clazzarrays[i])));
			students=sysManager.find(Student.STUDENT_QUERYBYCLAZZID,clazzparams);
			for(int j=0;j<coursearrays.length;j++){
  			   //course = new Course();
//				course.setId(Long.parseLong(StringUtils.trim(coursearrays[j])));
				course = (Course)sysManager.load(Course.class, Long.parseLong(StringUtils.trim(coursearrays[j])));
				score.setCourse(course);
				for(Student s:students){
					params.put("courseId", course.getId());
					params.put("studentId", s.getId());
					scores=sysManager.find(Score.COURSE_QUERYBYCOURSESTU,params);
					if(scores ==null || scores.size() == 0){
					  score.setStudent(s);
					  sysManager.save(score);
					  score.setId(null);
					}
					
				}
				
			}
		}
		}catch(Exception e){
			log.error("save score failed",e);
			return INPUT;
		}
		
		type="add";
		return SUCCESS;
	}
	
	//学生选课
	public String studentChoiceCourseSave(){
		try{
		student=(Student)getSession().getAttribute(Constants.LOGIN_STUDENT);
		String[] coursearrays=coursearray.split(",");
		score=new Score();
		for(int j=0;j<coursearrays.length;j++){
				course = (Course)sysManager.load(Course.class, Long.parseLong(StringUtils.trim(coursearrays[j])));
				score.setCourse(course);
				score.setStudent(student);
					params.put("courseId", course.getId());
					params.put("studentId", student.getId());
					scores=sysManager.find(Score.COURSE_QUERYBYCOURSESTU,params);
					if(scores ==null || scores.size() == 0){
					  
					  sysManager.save(score);
					   type="choice";
					   score.setId(null);
					}
				
				
			}
		}catch(Exception e){
			log.error(""+e);
		}
		return SUCCESS;
	}
	
	public String addScore(){
		try{
			courses = sysManager.find(Course.COURSE_LIST);
			if(course==null || student==null||score==null){
				return INPUT;
			}
			params.put("courseId", course.getId());
			params.put("studentId", student.getId());
			double point = score.getPoint();
			scores=sysManager.find(Score.COURSE_QUERYBYCOURSESTU,params);
			if(scores!=null && scores.size()>0){
				score = scores.get(0);
				score.setPoint(point);
				double avgPoint=PointUtil.change2Point(point);
				double credit=score.getCourse().getCredit();
				double conPoint=avgPoint*credit;
				score.setAvgPoint(avgPoint);
				score.setConPoint(conPoint);
				
			}else{
				course = (Course)sysManager.load(Course.class, course.getId());
				score.setCourse(course);
				student = (Student) sysManager.load(Student.class, student.getId());
				score.setStudent(student);
				score.setPoint(point);
				double avgPoint=PointUtil.change2Point(point);
				double credit=score.getCourse().getCredit();
				double conPoint=avgPoint*credit;
				score.setAvgPoint(avgPoint);
				score.setConPoint(conPoint);
			}
			scoreManager.saveOrUpdate(score);
			type="add";
		}catch(Exception e){
			log.error("add score failed",e);
			return INPUT;
		}
		return SUCCESS;
	}
	
	
	public String listScore(){
		LOG.info(score);
		try{
		if(score==null){
			score = new Score();
			course=new Course();
			student=new Student();
			score.setCourse(course);
			score.setStudent(student);
		}
		scores = scoreManager.queryScore(score.getStudent().getName(), score.getCourse().getName(), score.getCourse().getStatus(), getLimit());
		totalRows = scoreManager.countScore(score.getStudent().getName(), score.getCourse().getName(), score.getCourse().getStatus());
		}catch(Exception e){
			log.error("",e);
		}
		return SUCCESS;
	}
	public String editScore(){
		try{
			params.put("id", score.getId());
		    scores = sysManager.find(Score.SCORE_QUERYBYID,params);
		    if(scores!=null && scores.size()>0){
		    	score = scores.get(0);
		    }
		}catch(Exception e){
			log.error("",e);
		}
		return SUCCESS;
	}
	public String editScoreSave(){
		
		try{
			log.info(score);
			//double avgPoint=PointUtil.change2Point(score.getPoint());
			//score.setAvgPoint(avgPoint);
			Map<String,Object> paramsId = new HashMap<String,Object>();
			paramsId.put("id", score.getId());
			List<Score> scores1=new ArrayList<Score>();
			Score score1=new Score();
			scores1=sysManager.find(Score.SCORE_QUERYBYID,paramsId);
			if(scores1 !=null&& scores1.size()>0){
			   score1=scores1.get(0);
			   if((score1.getPoint()>0)&& (score1.getPoint()<60)){
				   score.setAvgPoint(1);
				   double credit=score1.getCourse().getCredit();
				   double conPoint=1*credit;
				   score.setConPoint(conPoint);
				   score.setMark(1);
			   }else if(score1.getMark() !=1){
				  
				    double avgPoint=PointUtil.change2Point(score.getPoint());
				    double credit=score1.getCourse().getCredit();
				    double conPoint=avgPoint*credit;
					score.setAvgPoint(avgPoint);
					score.setConPoint(conPoint);
				  }else{
					   score.setAvgPoint(1);
					   double credit=score1.getCourse().getCredit();
					   double conPoint=1*credit;
					   score.setConPoint(conPoint);
					   score.setMark(1);
				   }
			}
			params.put("studentName", score.getStudent().getName());
			students=sysManager.find(Student.STUDENT_QUERYBYNAME, params);
			if(students !=null&&students.size()>0){
				student=new Student();
				student=students.get(0);
				score.setStudent(student);
				params.clear();
				params.put("courseName", score.getCourse().getName());
				courses=sysManager.find(Course.COURSE_QUERYBYNAME,params);
				if(courses !=null&&courses.size()>0){
					course=new Course();
					course=courses.get(0);
					score.setCourse(course);
					
					sysManager.saveOrUpdate(score);
				}else{
					List list = new ArrayList();
					list.add("此名的课程不存在！");
					this.setActionErrors(list);
					return INPUT;
				}
			}else{
				List list = new ArrayList();
				list.add("此名的学生不存在！");
				this.setActionErrors(list);
				return INPUT;
			}
			
		
		}catch(Exception e){
			log.error("update score failed !",e);
			return INPUT;
		}
		
		return SUCCESS;
	}

	public String importInit(){
		return SUCCESS;
	}
	public String importScore(){
		Workbook book = null;
		Sheet sheet = null;
		Cell cell = null;
		int cNo =0;
		int sNo =0;
		int pIndex = 0;
		int point = 0;
		NumberCell nc = null;
		String value = null;
		try{
			if(excel!=null ){
				long fileLength = excel.length() / 1024;
				if (filerType(excelContentType) != null) {
					addFieldError("excel", "上传文件类型须为：.xls");
					return INPUT;
				}
				if (fileLength > 1024*2) {
					addFieldError("excel", "文件大小不可超过2M,请重新上传!");
					return INPUT;
				}
				book = Workbook.getWorkbook(excel);
				sheet = book.getSheet(0);
				int columns = sheet.getColumns();
				int rows = sheet.getRows();
				String content = "";
				scores = new ArrayList<Score>();
				for(int i =0;i<columns;i++){
					cell = sheet.getCell(i,1);
					log.info(cell.getContents());
					if (cell.getType() == CellType.LABEL) {// 如果数据类型是label的  
						content = cell.getContents();  
                    }
					if(content.equals("课程号")){
						cNo = i;
					}else if(content.equals("学生号")){
						sNo = i;
					}else if(content.equals("成绩")){
						pIndex = i;
					}
				}
				for(int i=2;i<rows;i++){
					score = new Score();
					for(int j=0;j<columns;j++){
						cell = sheet.getCell(j,i);
						if (cell.getType() == CellType.LABEL) {// 如果数据类型是label的  
							value = cell.getContents();  
	                    }else if (cell.getType() == CellType.NUMBER) {// 如果数据类型是NUMBER的  
	                    	nc = (NumberCell) cell;  
	                    	double p = nc.getValue();
	                    	point = (int)p;
	                    	value = String.valueOf(point);
	                    }
						if(j==cNo){
							if(StringUtils.isNotEmpty(value)){
								params.clear();
								params.put("code", value);
								courses=sysManager.find(Course.COURSE_QUERY,params);
								if(courses!=null && courses.size()>0){
									course = courses.get(0);
									score.setCourse(course);
								}else{
									break;
								}
							}
						}
						if(j==sNo){
							if(StringUtils.isNotEmpty(value)){
								params.clear();
								params.put("stuNo", value);
								students=sysManager.find(Student.STUDENT_QUERY,params);
								if(students!=null && students.size()>0){
									score.setStudent(students.get(0));
								}else{
									break;
								}
							}
						}
						if(j==pIndex){
							double avgPoint=PointUtil.change2Point(point);
						    double credit=course.getCredit();
						    double conPoint=avgPoint*credit;
							score.setAvgPoint(avgPoint);
							score.setConPoint(conPoint);
							score.setPoint(point);
						}
					}
					scores.add(score);
				}
				for(Score sc : scores){
					scoreManager.saveOrUpdate(sc);
				}
			}
			
		}catch(Exception e){
			log.error("",e);
		}finally{
			if(book!=null){
				book.close();
			}
		}
		
		
		
		return SUCCESS;
	}
	
	private String filerType(String type) {
		String[] allowsType = "application/vnd.ms-excel"
				.split(",");
		for (String allowType : allowsType) {
			if (type.equals(allowType)) {
				return null;
			}
		}
		return INPUT;
	}
	public String deleteScore(){
		sysManager.remove(Score.class, score.getId());
		return SUCCESS;
	}
	public static Logger getLog() {
		return log;
	}
	public static void setLog(Logger log) {
		ScoreAction.log = log;
	}
	
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public List<Course> getCourses() {
		return courses;
	}
	public void setCourses(List<Course> courses) {
		this.courses = courses;
	}
	
	
	public SysManager getSysManager() {
		return sysManager;
	}
	public void setSysManager(SysManager sysManager) {
		this.sysManager = sysManager;
	}
	public Map<String, Object> getParams() {
		return params;
	}
	public void setParams(Map<String, Object> params) {
		this.params = params;
	}
	
	
	public List<Score> getScores() {
		return scores;
	}
	public void setScores(List<Score> scores) {
		this.scores = scores;
	}
	public ScoreManager getScoreManager() {
		return scoreManager;
	}
	public void setScoreManager(ScoreManager scoreManager) {
		this.scoreManager = scoreManager;
	}
	public Score getScore() {
		return score;
	}
	public void setScore(Score score) {
		this.score = score;
	}
	public List<Student> getStudents() {
		return students;
	}
	public void setStudents(List<Student> students) {
		this.students = students;
	}
	public String getClazzarray() {
		return clazzarray;
	}
	public void setClazzarray(String clazzarray) {
		this.clazzarray = clazzarray;
	}
	public String getCoursearray() {
		return coursearray;
	}
	public void setCoursearray(String coursearray) {
		this.coursearray = coursearray;
	}
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}
	public Clazz getClazz() {
		return clazz;
	}
	public void setClazz(Clazz clazz) {
		this.clazz = clazz;
	}


	public Course getCourse() {
		return course;
	}


	public void setCourse(Course course) {
		this.course = course;
	}

	public File getExcel() {
		return excel;
	}

	public void setExcel(File excel) {
		this.excel = excel;
	}

	public String getExcelFileName() {
		return excelFileName;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}

	public String getExcelContentType() {
		return excelContentType;
	}

	public void setExcelContentType(String excelContentType) {
		this.excelContentType = excelContentType;
	}

	
	
}
